package communication.client;

import java.io.DataInputStream;
import java.io.IOException;

import java.net.Socket;

public class CommunicationClientThread extends Thread {
	private Socket socket = null;
	private CommunicationClient client = null;
	private DataInputStream streamIn = null;

	protected CommunicationClientThread(CommunicationClient client, Socket socket) {
		this.client = client;
		this.socket = socket;
		initiate();
		start();
	}

	protected void initiate() {
		try {
			streamIn = new DataInputStream(socket.getInputStream());
		} catch (IOException ioe) {
			System.out.println("Error getting input stream: " + ioe);
			client.stopClient();
		}
	}

	protected void close() {
		try {
			if (streamIn != null)
				streamIn.close();
		} catch (IOException ioe) {
			System.out.println("Error closing input stream: " + ioe);
		}
	}

	public void run() {
		while (true) {
			try {
				String msg = streamIn.readUTF();
				client.handleIncommingMessage(msg);
			} catch (IOException ioe) {
				System.out.println("Listening error: " + ioe.getMessage());
				client.stopClient();
			}
		}
	}
}